package com.laxcen.basiclib.ui.activity;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.githang.statusbar.StatusBarCompat;
import com.laxcen.basiclib.BaseConst;
import com.laxcen.basiclib.R;
import com.laxcen.basiclib.base.BaseActivity;
import com.laxcen.basiclib.core.permission.PermissionManager;
import com.laxcen.basiclib.core.updateH5.H5UpdateDialog;
import com.laxcen.basiclib.core.weex.WeexManager;
import com.laxcen.basiclib.core.weex.hotreload.HotReloadManager;
import com.laxcen.basiclib.core.weex.util.AppConfig;
import com.laxcen.basiclib.core.weex.util.Constants;
import com.laxcen.basiclib.utils.CommonUtil;
import com.taobao.weex.utils.WXLogUtils;
import com.taobao.weex.utils.WXSoInstallMgrSdk;

import org.json.JSONException;
import org.json.JSONObject;

public abstract class WeexActivity extends BaseActivity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weex);
        initPermission();
    }


    private void initPermission(){
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.white), true);
        PermissionManager.get(this).check(BaseConst.permission, () -> {
            init();
            initRender();
            initAfter();
        });
    }

    private ProgressBar mProgressBar;
    private TextView mTipView;
    private FrameLayout mContainer;
    private boolean mFromSplash = false;
    private HotReloadManager mHotReloadManager;
    private void init(){
        mProgressBar = findViewById(R.id.progress);
        mTipView =  findViewById(R.id.index_tip);
        mContainer = findViewById(R.id.container);

        WeexManager.getInstance().setContainer(mContainer);
        WeexManager.getInstance().load(this);

    }
    //监听H5更新状态处理
    public static final String ON_WEB_UPDATE = "ON_WEB_UPDATE";
    private void initAfter(){
        api.checkUpdate();

        //监听更新状态
        broadcastManager.register(ON_WEB_UPDATE, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String type = intent.getStringExtra("type");
                switch (type) {
                    case BaseConst.ACTION_DOWNLOADED_H5_UPLOAD:
                        //开始更新 弹出更新进度条
                        String path = intent.getStringExtra("path");
                        H5UpdateDialog.update(WeexActivity.this, path);
                        break;
                    case BaseConst.ACTION_H5_UPLOADED:
                        //更新完 重新加载页面
                        api.loadH5Config(true);
                        String url = CommonUtil.getWebRoot(WeexActivity.this);
                        WeexManager.getInstance().loadUrl(url);
                        break;
                }
            }
        });
    }

    private void initRender(){
        Intent intent = getIntent();
        Uri uri = intent.getData();
        String from = intent.getStringExtra("from");
        mFromSplash = "splash".equals(from);

        if (uri == null) {
            uri = Uri.parse("{}");
        }
        if (uri != null) {
            try {
                JSONObject initData = new JSONObject(uri.toString());
                String bundleUrl = initData.optString("WeexBundle", null);
                if (bundleUrl != null) {
                    WeexManager.getInstance().mUri = Uri.parse(bundleUrl);
                }

                String ws = initData.optString("Ws", null);
                if (!TextUtils.isEmpty(ws)) {
                    mHotReloadManager = new HotReloadManager(ws, new HotReloadManager.ActionListener() {
                        @Override
                        public void reload() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    WeexManager.getInstance().createWeexInstance();
                                    WeexManager.getInstance().renderPage();
                                }
                            });
                        }

                        @Override
                        public void render(final String bundleUrl) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    WeexManager.getInstance().createWeexInstance();
                                    WeexManager.getInstance().loadUrl(bundleUrl);
                                }
                            });
                        }
                    });
                } else {
                    WXLogUtils.w("Weex", "can not get hot reload config");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (WeexManager.getInstance().mUri == null) {
            WeexManager.getInstance().mUri = Uri.parse(AppConfig.getLaunchUrl());
        }

        if (!WXSoInstallMgrSdk.isCPUSupport()) {
            mProgressBar.setVisibility(View.INVISIBLE);
            mTipView.setText("CPU型号不支持！");
            return;
        }

        String url = getUrl(WeexManager.getInstance().mUri);
        WeexManager.getInstance().loadUrl(url);
    }

    private String getUrl(Uri uri) {
        String url = uri.toString();
        String scheme = uri.getScheme();
        if (uri.isHierarchical()) {
            if (TextUtils.equals(scheme, "http") || TextUtils.equals(scheme, "https")) {
                String weexTpl = uri.getQueryParameter(Constants.WEEX_TPL_KEY);
                if (!TextUtils.isEmpty(weexTpl)) {
                    url = weexTpl;
                }
            }
        }
        return url;
    }

    protected void preRenderPage() {
        mProgressBar.setVisibility(View.VISIBLE);
    }


    @Override
    protected void onDestroy() {
        Log.e("onDestroy","onDestroy");
        WeexManager.getInstance().onDestroy();
        broadcastManager.unregister(ON_WEB_UPDATE);
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        WeexManager.getInstance().onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        WeexManager.getInstance().onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        WeexManager.getInstance().onStop();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        WeexManager.getInstance().onActivityResult(requestCode,resultCode,data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        WeexManager.getInstance().onRequestPermissionsResult(requestCode,permissions,grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}